package com.hitqz.robot.common.core.util;

import java.lang.reflect.Field;

/**
 * 对象属性转换类型
 *
 * @author kehanjiang
 * @date 2024/03/05
 */
public class HitConvertUtils {

    /**
     * 将一个对象里所有的空值属性设置成null
     *
     * @param o
     * @return
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static <T> T emptyToNull(T o) {
        Class c = o.getClass();
        Class sc = c.getSuperclass();
        if (null != sc) {
            recursionNull(sc, o);
        }
        try {
            Field[] fs = c.getDeclaredFields();
            for (Field f : fs) {
                f.setAccessible(true);
                String st = f.get(o) + "";
                String str = st.replaceAll(" ", "");
                if (str.equals("") || str == null || str.equals("null")) {
                    f.set(o, null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return o;
    }

    /**
     * 判断是否有超类，若有则继续将超类的空值置空
     *
     * @param sc
     * @param o
     * @return
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    private static <T> T recursionNull(Class sc, T o) {
        Class c = sc.getSuperclass();
        if (null != c) {
            recursionNull(c, o);
        }
        try {
            Field[] fs = sc.getDeclaredFields();
            for (Field f : fs) {
                f.setAccessible(true);
                String st = f.get(o) + "";
                String str = st.replaceAll(" ", "");
                if (str.equals("") || str == null || str.equals("null")) {
                    f.set(o, null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return o;
    }

}